﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using AdsRemote;
using AdsRemote.Common;
using System.Diagnostics;
using TwinCAT.Ads;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            PLC plc = new PLC("192.168.179.101.1.1");
            plc.DeviceReady += Plc_DeviceReady;
            plc.DeviceLost += Plc_DeviceLost;
            //Var<short> main_count = plc.Var<short>("MAIN.count");

            //Var<short> shijicaigao = plc.Var<short>(".SHIJICAIGAO");
            //Var<bool> GEMEI_END_L = plc.Var<bool>(".GEMEI_END_L");
            //Var<bool> GEMEI_END_R = plc.Var<bool>(".GEMEI_END_R");


            Console.CancelKeyPress += (sender, e) =>
            {
                e.Cancel = false; //true: 不导致退出。false: 会导致退出
                System.Console.WriteLine("You have Press Ctrl+C");
                if (!e.Cancel)
                {
                    System.Console.WriteLine("App Exit.");
                    Process.GetCurrentProcess().Kill();
                }
            };

            //TcAdsClient tc = new TcAdsClient();
            //tc.Connect("192.168.179.101.1.1", 801);
            //int[] arr = new int[250];
            //arr = (int[])tc.ReadSymbol(".SHIJICAIGAO", typeof(Array<int>), false);
            //Console.WriteLine(arr.ToString());




            //GEMEI_END_L.ValueChanged += (sender,e) =>
            //{
            //    System.Console.WriteLine("GEMEI_END_L.ValueChanged：" + sender.ToString());
            //};

            //shijicaigao.ValueChanged += (sender, e) =>
            //{
            //    System.Console.WriteLine("shijicaigao.ValueChanged：" + sender.ToString());
            //};
            AdsRemote.ArrayVar arrayVar = new AdsRemote.ArrayVar(".SHIJICAIGAO",801);
            
            while (true)
            {
                Thread.Sleep(1000);
                short[] v = plc.ReadArrayByName(arrayVar, 250);
                System.Console.WriteLine("{0},{1},{2},{3},{4}", v[0], v[1], v[2], v[3], v[4]);                         
            }
            Console.ReadLine();
        }

        private static void Plc_DeviceReady(object sender, AdsDevice e)
        {
            Console.WriteLine("READY [" + e.Address.Port.ToString() + "]");
        }

        private static void Plc_DeviceLost(object sender, AdsDevice e)
        {
            Console.WriteLine("READY [" + e.Address.Port.ToString() + "]");
        }
    }
}
